
const { ccclass, property, menu } = cc._decorator;


/** PageViewRepeat
 *  在原pageview基础上  123
 * 
 *  左右各加一个节点赋值尾部和头部的数据   123 => 31231
 *  每当滑动到头部时  3[1]231 -> [3]1231   
 *  跳转到最后一个数据的位置 [3]1231 -> 312[3]1
 *  滑动到尾部时同理
 */
@ccclass
@menu("自定义组件/PageView/循环滚动")
export default class PageViewRepeat extends cc.Component {


    @property(cc.PageView)
    pv_PageView: cc.PageView = null

    @property(cc.Prefab)
    Item_Prefab: cc.Prefab = null;
    content: cc.Node = null;
    onLoad() {
        this.pv_PageView || (this.pv_PageView = this.node.getComponent(cc.PageView))
        this.pv_PageView || cc.error("未正确取得数据")
        this.content = this.pv_PageView.content;


    }
    onEnable() {
        this.pv_PageView.node.on('scroll-ended', this._PageTurning, this)
        // this.pv_PageView.node.on('page-turning', this._PageTurning, this)//PageTurning  有几率不触发
    }
    onDisable() {
        if (this.pv_PageView.node) {
            this.pv_PageView.node.off('scroll-ended', this._PageTurning, this)
            // this.pv_PageView.node.off('page-turning', this._PageTurning, this)
        }
    }
    _PageTurning() {
        let currPageIndex = this.pv_PageView.getCurrentPageIndex();

        cc.log("OnPageViewEvent begin, page index=" + currPageIndex);


        let pages = this.pv_PageView.getPages();
        if (currPageIndex == 0) {
            this.pv_PageView.scrollToPage(pages.length - 2, 0);
            this.pv_PageView.setCurrentPageIndex(pages.length - 2);
        }
        else if (currPageIndex == (pages.length - 1)) {
            this.pv_PageView.scrollToPage(1, 0);
            this.pv_PageView.setCurrentPageIndex(1);
        }

        cc.log("OnPageViewEvent end, page index=" + currPageIndex);
    }

    setData(length: number, callBack: (item_sc: any, index: number) => void) {
        this.pv_PageView.removeAllPages();
        let len = length;
        if (len <= 0 || !callBack) {
            //没有数据
            return;
        }
        //节点上是第一个  数据上是最后一个
        let itemFrist_sc = this.createPage()
        callBack(itemFrist_sc, length - 1)

        //正常顺序
        for (let i = 0; i < len; i++) {
            let item_sc = this.createPage()
            callBack(item_sc, i)
        }

        //节点上是最后一个  数据上是第一个
        let itemLast_sc = this.createPage()
        callBack(itemLast_sc, 0)


        this.pv_PageView.scrollToPage(1, 0)
    }
    /** 创建一个节点
     *  @returns class
     */
    createPage() {
        let item = cc.instantiate(this.Item_Prefab)
        this.pv_PageView.addPage(item)
        return item.getComponent(item.name)
    }
}
